package com.fulu.game.bi.service.impl.auth.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.fulu.game.bi.common.util.lang.GenIdUtil;
import com.fulu.game.bi.entity.po.auth.BiUser;
import com.fulu.game.bi.entity.vo.auth.user.UserLoginDisplayVO;
import com.fulu.game.bi.service.impl.auth.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SaltedAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * 秘钥比较
 */
@Slf4j
public class BiUsernamePasswordMatcher implements CredentialsMatcher {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String salt = "";
        if (info instanceof SaltedAuthenticationInfo) {
            ByteSource bs = ((SaltedAuthenticationInfo) info).getCredentialsSalt();
            try {
                salt = new String(bs.getBytes(), StandardCharsets.UTF_8);
            } catch (Exception e) {
                log.info("解析salt错误 {}", e.getMessage());
            }
        }

        char[] chars = ((UsernamePasswordToken) token).getPassword();
        String data = String.valueOf(chars) + salt;
        String md5Str = SecureUtil.md5(data);

        boolean match = Objects.equals(md5Str, info.getCredentials());
        if (!match) {
            log.info("密码不匹配, 请求的密码: {}, 实际的密码是 {}", md5Str, info.getCredentials());
        }

        syncCache(info);

        return match;
    }

    /**
     * 同步到缓存
     */
    protected void syncCache(AuthenticationInfo info) {
        //登录成功保存token和用户信息到redis
        BiUser admin = (BiUser) info.getPrincipals().getPrimaryPrincipal();
        String genToken = GenIdUtil.GetToken();

        UserLoginDisplayVO currentUser = new UserLoginDisplayVO();
        currentUser.setId(admin.getId());
        currentUser.setName(admin.getName());
        currentUser.setUsername(admin.getUsername());
        currentUser.setStatus(admin.getStatus());
        currentUser.setToken(genToken);

        Map<String, Object> cacheMap = BeanUtil.beanToMap(currentUser);

        tokenService.createUserMap(genToken, cacheMap);

        BiSubject subject = ((BiSubject) SecurityUtils.getSubject());
        subject.setToken(genToken);
        subject.setCurrentUser(currentUser);

        log.info("当前的用户信息是 {}", subject.getCurrentUser());
    }

}
